package com.panopset.io;

import com.panopset.Alert;
import com.panopset.Util;
import java.io.File;

/**
 * Process all files in a directory, and it's subdirectories.
 *
 * @author Karl Dinwiddie
 *
 */
public abstract class DirectoryProcessor {

    /**
     * Directory to process.
     */
    private final File d;

    /**
     * Every file in the directory may be processed, just override this method.
     * @param f File to process
     */
    protected abstract void process(File f);

    /**
     * Process a directory and its subdirectories.
     * @param dir Top directory to process
     */
    public DirectoryProcessor(final File dir) {
        this.d = dir;
    }

    /**
     * Do the traversal.
     */
    public final void exec() {
        traverse(this.d);
        Alert.green(Util.x("Task complete."));
    }

    /**
     * Traverse the directory or process the file.
     * @param file File.
     */
    private void traverse(final File file) {
        if (file.isFile()) {
            process(file);
        } else {
            for (File f : file.listFiles()) {
                traverse(f);
            }
        }
    }
}
